package com.wertop.viid.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.wertop.viid.common.annotation.LogOperation;
import com.wertop.viid.common.enums.InfoKind;
import com.wertop.viid.common.result.ConfirmStatusType;
import com.wertop.viid.common.result.ResponseStatusListObject;
import com.wertop.viid.common.result.ResponseStatusObject;
import com.wertop.viid.common.utils.Base64Utils;
import com.wertop.viid.common.utils.DateUtils;
import com.wertop.viid.common.validator.ValidatorUtils;
import com.wertop.viid.dao.RmsScreenshotDao;
import com.wertop.viid.dao.RmsScreenshotVehicleDao;
import com.wertop.viid.dto.MotorVehicleListObject;
import com.wertop.viid.dto.MotorVehicleObject;
import com.wertop.viid.dto.SubImageInfoObject;
import com.wertop.viid.entity.CmsDevice;
import com.wertop.viid.entity.CmsVehiclePath;
import com.wertop.viid.entity.RmsScreenshot;
import com.wertop.viid.entity.RmsScreenshotVehicleInfo;
import com.wertop.viid.service.CmsVehiclePathService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description MotorVehicleController
 * @Author yempty
 * @Date 2020/6/18 11:27
 */
@Slf4j
@RestController
@RequestMapping("MotorVehicles")
@Api(tags = "机动车相关接口")
public class MotorVehicleController {
    @Resource
    private CmsVehiclePathService cmsVehiclePathService;
    @Resource
    private RmsScreenshotDao rmsScreenshotDao;
    @Resource
    private RmsScreenshotVehicleDao rmsScreenshotVehicleDao;

//        private final String imgUrl = "C:/Users/wertop/Desktop/vehicle20211028/";
    private final String imgUrl = "/upload/xmyc/picture/";

    @PostMapping
    @ApiOperation("机动车批量新增")
    @LogOperation("机动车批量新增")
    public ResponseStatusListObject register(@RequestBody MotorVehicleListObject motorVehicleListObject) {
        List<CmsVehiclePath> cmsVehiclePathList = new ArrayList<>();
        List<RmsScreenshot> rmsScreenshotList = new ArrayList<>();
        boolean insertFlag = true;
        List<ResponseStatusObject> list = new ArrayList<>(motorVehicleListObject.getMotorVehicleObjects().size());
        ResponseStatusObject responseStatusObject;
        String errMsg;
        InfoKind infoKind;
        for (MotorVehicleObject motorVehicleObject : motorVehicleListObject.getMotorVehicleObjects()) {
            // 检验参数
            errMsg = ValidatorUtils.validateEntity(motorVehicleObject);
            if (StringUtils.isBlank(errMsg)) {
                infoKind = InfoKind.getByValue(motorVehicleObject.getInfoKind());
                if (infoKind == null) {
                    errMsg += "信息分类的值不符合要求.";
                } else {
                    switch (infoKind) {
                        case AUTO:
                            if (StringUtils.isBlank(motorVehicleObject.getDeviceId())) {
                                errMsg += "自动采集，设备编码必须填写.";
                            }
                            if (motorVehicleObject.getLeftTopX() == null || motorVehicleObject.getLeftTopY() == null
                                    || motorVehicleObject.getRightBtmX() == null || motorVehicleObject.getRightBtmY() == null) {
                                errMsg += "自动采集，记录车轮廓矩形框的左上角坐标和右下角坐标必须填写.";
                            }
                            break;
                        case MANUAL:
                            if (motorVehicleObject.getMarkTime() == null) {
                                errMsg += "人工采集，位置标记时间必须填写.";
                            }
                            if (motorVehicleObject.getAppearTime() == null) {
                                errMsg += "人工采集，出现时间必须填写.";
                            }
                            if (motorVehicleObject.getDisappearTime() == null) {
                                errMsg += "人工采集，消失时间必须填写.";
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            if (StringUtils.isBlank(errMsg)) {
                responseStatusObject = ResponseStatusObject.create(motorVehicleObject.getMotorVehicleId(), ConfirmStatusType.OK);
            } else {
                responseStatusObject = ResponseStatusObject.create(motorVehicleObject.getMotorVehicleId(), ConfirmStatusType.Validate_Error.getCode(), errMsg);
            }
            list.add(responseStatusObject);
            //todo 信息入库
//            CmsVehiclePath cmsVehiclePath = new CmsVehiclePath();
//            BeanUtils.copyProperties(motorVehicleObject, cmsVehiclePath);
//            cmsVehiclePath.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
//            cmsVehiclePathList.add(cmsVehiclePath);
            insertFlag = ObjectUtil.isNotEmpty(motorVehicleObject.getDeviceId());
            if (insertFlag) {
                List<CmsDevice> device  = rmsScreenshotDao.getDevice(motorVehicleObject.getDeviceId());
                insertFlag = ObjectUtil.isNotEmpty(device) && 1 == device.get(0).getIsViid();
                log.info("----------设备信息result：{}",device);
            }
            log.info("----------设备编号为：{}，图片处理入库开关状态：{}", motorVehicleObject.getDeviceId(), insertFlag);
            RmsScreenshotVehicleInfo info = new RmsScreenshotVehicleInfo();

            info.setColor(motorVehicleObject.getVehicleColor());
            info.setVehicleId(motorVehicleObject.getPlateNo());
            info.setType(motorVehicleObject.getVehicleModel());
            info.setVehicleClass(motorVehicleObject.getVehicleClass());
            String tableNameVehicle = "rms_screenshot_vehicle_info_" + DateUtils.formatMonth(new Date());
            if (ObjectUtil.isNotEmpty(motorVehicleObject.getSubImageList())) {
                if (ObjectUtil.isNotEmpty(motorVehicleObject.getSubImageList().getSubImageInfoObjects())) {
                    if (motorVehicleObject.getSubImageList().getSubImageInfoObjects().size() > 1) {
                        if (insertFlag) {
                            rmsScreenshotVehicleDao.insertScreenshotVehicle(info, tableNameVehicle);
                        }
                        RmsScreenshot rmsScreenshot = new RmsScreenshot();
                        rmsScreenshot.setType(2);
                        rmsScreenshot.setDetailInfoId(info.getId());
                        rmsScreenshot.setLeftTopX(motorVehicleObject.getLeftTopX().toString());
                        rmsScreenshot.setLeftTopY(motorVehicleObject.getLeftTopY().toString());
                        rmsScreenshot.setRightBottomX(motorVehicleObject.getRightBtmX().toString());
                        rmsScreenshot.setRightBottomY(motorVehicleObject.getRightBtmY().toString());
                        //图片信息
                        List<SubImageInfoObject> subImageInfoObjects = motorVehicleObject.getSubImageList().getSubImageInfoObjects();
                        String url = imgUrl + DateUtils.formatMonth(new Date()) + "/";
                        File file = new File(url);
                        if (!file.exists()) {
                            file.mkdirs();
                        }
                        subImageInfoObjects.stream().forEach(x -> {
                            String fileName = url + DateUtils.format(DateUtil.date(x.getShotTime()), "yyyy-MM-dd-HH-mm-ss") + "-" + x.getType() + ".png";
                            Base64Utils.Base64ToImage(x.getData(), fileName);
                            if (x.getType().equals("14")) {
                                rmsScreenshot.setSnapshot(fileName);
                                rmsScreenshot.setScreenshotTime(DateUtils.format(DateUtil.date(x.getShotTime()), "yyyy-MM-dd HH:mm:ss"));
                            } else if (x.getType().equals("02") || x.getType().equals("01") || x.getType().equals("09")) {
                                rmsScreenshot.setScreenshot(fileName);
                            }
                        });
                        rmsScreenshot.setWebcamId(motorVehicleObject.getDeviceId());
                        rmsScreenshot.setIsDis(0);
                        rmsScreenshot.setPictureId(0L);
                        rmsScreenshot.setObjectId(0L);
                        rmsScreenshot.setMatched("0%");
                        rmsScreenshot.setTaskTypeCode(2);
                    }
                } else {
                    throw new IllegalArgumentException("motorVehicleObject.getSubImageList().getSubImageInfoObjects() is empty.");
                }
            } else {
                throw new IllegalArgumentException("motorVehicleObject.getSubImageList() is empty.");
            }

        }
        String tableName = "rms_screenshot_" + DateUtils.formatMonth(new Date());
        if (ObjectUtil.isNotEmpty(rmsScreenshotList)&& insertFlag) {
            rmsScreenshotDao.insertScreenshot(rmsScreenshotList, tableName);
        }
//        cmsVehiclePathService.saveBatch(cmsVehiclePathList);

        return ResponseStatusListObject.create(list);
    }
}
